package com.star.gc4.controller;


import cn.hutool.extra.mail.MailUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.star.gc4.common.R;
import com.star.gc4.common.VerCodeGenerateUtil;
import com.star.gc4.dto.UserDto;
import com.star.gc4.entity.User;
import com.star.gc4.service.UserService;
import com.star.gc4.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/user")



public class UserController {

    final Integer authority = 0;

    @Autowired
    private UserService userService;





    //非管理员用户登录
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user) {

        System.out.println("用户邮箱："+user.getEmail()+"*****\n"+"用户密码："+user.getPassword()+"*****\n");
        String password = user.getPassword();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, user.getEmail());
        User u = userService.getOne(queryWrapper);


        if( u == null){
            return R.error("不存在该用户");
        }


        if(!u.getPassword().equals(password)){
            return R.error("用户名或密码错误");
        }
        request.getSession().setAttribute("user", u.getId());
        return R.success(u);
    }

    //管理员登录
    @PostMapping("/adminLogin")
    public R<User> adminLogin(HttpServletRequest request, @RequestBody User user) {
        String password = user.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, user.getEmail()).eq(User::getAuthority,authority);
        User u = userService.getOne(queryWrapper);
        if(u.getAuthority()!=0){
            return R.error("没有登录权限！");
        }
        if (u == null) {
            return R.error("不存在该用户");
        }
        if (!u.getPassword().equals(password)) {
            return R.error("用户名或密码错误");
        }
        request.getSession().setAttribute("user", u.getId());
        return R.success(u);
    }


    //邮箱验证
    @RequestMapping ("/mail")
    public R<String> sendSimpleMail(String mail,HttpServletRequest request) {

        if(mail==null){
            System.out.println("邮箱为空");
        }
        //获取验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        // 收件人电子邮箱
        String to = mail;

        // 设置内容
        String content = "【在线音乐播放器注册】您的邮件验证码是"+code+"，识别码是KIL。请核对识别码再输入验证码，有效期3分钟。";

        try {
            MailUtil.send(to, "轩", content, false);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        request.getSession().setAttribute("verCode", code);
        return R.success("发送短信验证码成功");


    }

    //用户注册
    @PostMapping("/register")
    public R<String> register(@RequestBody UserDto userDto,HttpServletRequest request) {

        //获取sendSimpleMail方法中的mail
        String o = (String) request.getSession().getAttribute("verCode");

        if (o == null) {
            return R.error("请输入验证码！");
        }
        if(!o.equals(userDto.getVerCode())){
            return R.error("验证码错误！");
        }

        //帐号密码
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String name = userDto.getUsername();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        User u = userService.getOne(queryWrapper);

        if (u != null) {
            return R.error("该帐号已被注册!");
        }

        User user = new User();

        user.setPassword(password);
        user.setEmail(email);
        user.setUsername(name);
        user.setAuthority(1);
        userService.save(user);
        return R.success("注册成功");
    }

    @PostMapping("/forget")
    public R<String> forget(String email,String code,String password,HttpServletRequest request,String flag) {

        //获取sendSimpleMail方法中的mail
        String o = (String) request.getSession().getAttribute("verCode");
        Integer userid = (Integer) request.getSession().getAttribute("user");
        if (code == null) {
            return R.error("请输入验证码！");
        }
        if(!o.equals(code)){
            return R.error("验证码错误！");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (flag.equals("1") ){
            queryWrapper.eq(User::getEmail, email);
            User one = userService.getOne(queryWrapper);
            if(one ==null){
                return R.error("该账户不存在，请注册");
            }

        }else if(flag.equals("2")){
            queryWrapper.eq(User::getId, userid);
            User one = userService.getOne(queryWrapper);
            if(!email.equals(one.getEmail())){
                return R.error("非本人邮箱");
            }
        }


        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("password",password);
        updateWrapper.eq("email",email);
        userService.update(updateWrapper);
        return R.success("修改成功");
    }




    //用户名和密码修改
    @PostMapping("/modifyPassword")
    public R<String> modifyPassword(HttpServletRequest request, @RequestBody UserDto userDto) {
        //获取登录用户的Session
        Object o = request.getSession().getAttribute("user");
        if (o == null)
            return R.error("用户未登录");
        Integer userId = (Integer) o;

        User user = userService.getById(userId);

        if (!user.getPassword().equals(userDto.getOldPassword())) {
            return R.error("旧密码错误");
        }
        user.setPassword(userDto.getPassword());
        userService.updateById(user);
        user.setUsername(userDto.getUsername());
        userService.updateById(user);
        return R.success("信息修改成功");
    }

    //vip注册
    @PostMapping("/vip")
    public R<String> vip(HttpServletRequest request){
        int o = (int) request.getSession().getAttribute("user");
        User u = userService.getById(o);
        u.setAuthority(2);
        userService.updateById(u);
        return R.success("恭喜您成为了会员！");
    }


    //用户信息分页查询
    @GetMapping("/page")
    public R<Page<User>> page(int page, int pageSize, String email){

        //构造分页构造器
        Page<User> pageInfo = new Page<>(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(!StringUtils.isEmpty(email), User::getEmail, email);
        //添加排序条件
        queryWrapper.orderByDesc(User::getId);

        //执行查询
        userService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    //用户信息删除
    @PostMapping("/delete")
    public R<String> delete( Integer id) {
        try {
            userService.removeById(id);
        } catch (Exception e) {
            R.error("删除员工失败！");
        }
        return R.success("删除成功！");
    }

}
